﻿using AiMoWindows.CodeScripts;
using AiMoWindows.Localization;
using System.Windows;

namespace AiMoWindows.MainActions.ScriptActions.SubActions
{
    /// <summary>
    /// 新开代码窗口，清理代码窗口
    /// </summary>
    class ClearScriptsAction(ActionsController actions, ScriptManager scriptManager)
    {
        readonly ActionsController actions = actions;
        readonly ScriptManager scriptManager = scriptManager;
        public void NewScriptWindow()
        {
            // 实现创建新脚本窗口的逻辑
            if (!Entrance.AiMoProgram.Instance.OpenNewAimoScriptForm(withDefaultExample: false, out string error))
            {
                actions.ClearDebugPrint();
                actions.Printer.PrintDebug(error);
            }
        }
        /// <summary>
        /// 取消返回True
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CheckNotSaveOrCancel()
        {
            actions.ClearDebugPrint();
            if (!await actions.SyncAction.SyncScriptsWithFormat())
            {
                // 无法同步，格式有误
                MessageBoxResult re = MessageBox.Show(actions.MainWindow,
                    Local.Get("Current script has wrong format, and cannot save. Do you want to continue without save?"),
                    Local.Get("Warning"), MessageBoxButton.YesNo);
                return re != MessageBoxResult.Yes;// 不是yes说明不可以直接删除，返回取消
            }
            scriptManager.CheckNotSave(actions.MainWindow, out bool cancel, out string printInfo);
            actions.Printer.PrintDebug(printInfo);
            return cancel;
        }

        public async void ClearScript()
        {
            if (await CheckNotSaveOrCancel())
            {
                return;
            }
            // 实现清除脚本的逻辑
            scriptManager.ResetToNew();
            // 同步AiMoScript修改到前台
            await actions.SyncAction.BringBackScriptToEditor();
            // Clear Undo Records
            actions.Editor.Document.UndoStack.ClearAll();
        }
    }
}
